<template>
  <div class="conetr h-full flex flex-col" v-loading="loading">
    <div class="center-board">
      <div class="center-title">
        <h3>品类预算</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          @click="handleSubmit"
          :disabled="!canEdit"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      class="form flex flex-col flex-1 overflow-auto"
      :disabled="!canEdit"
    >
      <BasePageTable
        :table-data="formData.tableData"
        :table-columns-data="tableColumnsData"
        height="100%"
        class="flex-1 overflow-auto"
      >
        <template #brandId="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandId'" :rules="formRules.brandId">
            <div class="flex">
              <el-select
                v-model="row.brandId"
                placeholder="请选择品牌"
                clearable
                filterable
                class="mr-2.5"
                @change="handleChangeBrand($event, row)"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  class="!w-[180px]"
                  :label="item.brandName"
                  :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>
        </template>
        <template #brandName="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandName'" :rules="formRules.brandName">
            <el-input
              v-model="row.brandName"
              placeholder="请输入品牌"
              @change="row.brandId = ''"
            ></el-input>
          </el-form-item>
        </template>
        <template #budgetAmount="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.budgetAmount'"
            :rules="formRules.budgetAmount"
          >
            <el-input-number
              v-model.number.trim="row.budgetAmount"
              :min="0"
              type="number"
              placeholder="请输入预算金额"
            />
          </el-form-item>
        </template>
        <template #categoryId="{ row, index }">
          {{ row.categoryText }}
          <!-- <el-form-item
            :prop="'tableData.' + index + '.categoryId'"
            :rules="formRules.categoryId"
          >
            <el-cascader
              v-model="row.categoryId"
              placeholder="请选择分类"
              style="width: fit-content"
              :options="getMaterialCategoryList"
              :show-all-levels="false"
              :props="{
                value: 'id',
                label: 'name',
              }"
              @change="(row) => handleAddAll(row)"
            />
          </el-form-item> -->
        </template>
        <template #operation="{ row, index }">
          <el-button link type="danger" icon="Delete" @click="handleDelete(index)">删除</el-button>
        </template>
      </BasePageTable>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import HouseAPI from "@/api/house";
import CommonAPI, { BrandForm } from "@/api/system/common";
import BasePageTable from "@/components/BasePageTable/index.vue";
import { useCategory } from "@/hooks/useCategory";

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);
const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const currentRow = ref({});
const brandList = ref([]);
const loading = ref(false);
const { getMaterialCategoryList, materialCategoryList, getMaterialCategory } = useCategory();
const tableColumnsData = ref([
  {
    prop: "categoryId",
    label: "分类",
    showOverflowTooltip: true,
    customSlot: "categoryId",
  },
  {
    prop: "brandId",
    label: "品牌",
    showOverflowTooltip: true,
    customSlot: "brandId",
    width: 200,
  },

  {
    prop: "brandName",
    label: "自定义品牌",
    showOverflowTooltip: true,
    customSlot: "brandName",
    width: 200,
  },
  {
    prop: "budgetAmount",
    label: "预算金额（元）",
    showOverflowTooltip: true,
    customSlot: "budgetAmount",
    width: 200,
  },
  {
    prop: "remark",
    label: "驳回理由",
    showOverflowTooltip: true,
    width: 200,
  },
  // {
  //   prop: "operation",
  //   label: "操作",
  //   width: 100,
  //   align: "center",
  //   customSlot: "operation", // 自定义插槽名称
  // },
]);

const defaultFormData = {
  tableData: [],
};
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
  budgetAmount: [
    { type: "number", message: "预算金额必须为数字" },
    { type: "number", max: 999999999, message: "预算金额超出最大值" },
    { required: true, message: "请输入预算金额", trigger: "blur" },
  ],
});
function backTo() {
  emit("backTo");
}
async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    loading.value = true;
    const params = formData.value.tableData.map((item) => {
      //超过两就传最后一个
      let categoryId = item.categoryId;
      if (Array.isArray(item.categoryId) && item.categoryId.length > 0) {
        categoryId = item.categoryId[item.categoryId.length - 1];
      }
      return {
        ...item,
        categoryId,
      };
    });
    await HouseAPI.houseDesignBudgetEdit(params);
    ElMessage.success("成功");
    emit("loadData");
    loading.value = false;
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    loading.value = false;
    console.log("error", error);
    //ElMessage.error("失败");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}
const canEdit = ref(true);
async function showModal(val, cannotEdit = false) {
  dialog.visible = true;
  currentRow.value = val;
  await getMaterialCategory();
  getBrand();
  const { houseDesignBudgetVOList } = val["house"];
  if (houseDesignBudgetVOList?.length > 0) {
    formData.value.tableData = houseDesignBudgetVOList;
  } else {
    formData.value.tableData = handleAddAll();
  }
  canEdit.value = !cannotEdit;
}

function handleDelete(index) {
  formData.value.tableData.splice(index, 1);
}

async function getBrand() {
  loading.value = true;
  try {
    const params: BrandForm = {
      keyword: "",
    };
    brandList.value = await CommonAPI.getBrand(params);
    loading.value = false;
  } catch (e) {
    console.log(e);
  }
}

// function handleAdd() {
//   formData.value.tableData.push({
//     brandId: "",
//     brandName: "",
//     budgetAmount: "",
//     categoryId: "",
//     useAmount: "",
//     houseId: currentRow.value.houseId,
//   });
// }
/**
 * 新增固定的值，所有二级的搜需要填写，不用新增了
 */
function handleAddAll() {
  let secontList = materialCategoryList.value.filter((item) => {
    return item.level === 2;
  });
  return secontList.map((item) => {
    return {
      brandName: "",
      budgetAmount: "",
      categoryId: [item.id],
      categoryText: item.name,
      budgetAmount: 0,
      houseId: currentRow.value.houseId,
    };
  });
}

function handleChangeBrand(id, row) {
  if (!id) return (row.brandName = "");
  const { brandName } = brandList.value.find((item) => item.id === id);
  row.brandName = brandName;
}

function handleChangeBrandId(row) {
  row.brandName = "";
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
.conetr {
  background-color: #fff;
  position: relative;
  flex: 1;
  box-sizing: border-box;
  padding: 10px 20px;

  .center-board {
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }
  }
}
</style>
